package com.roadjava.rbac.service.websocket;

import com.roadjava.rbac.bean.vo.Message;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class InMemoryMessageStore {

    public static final ConcurrentHashMap<String, CopyOnWriteArrayList<Message>> messageStore = new ConcurrentHashMap<>();

    // 将消息添加到存储中
    public static void addMessage(Message message) {
        String key = generateKey(message.getFromUserId(), message.getToUserId());
        messageStore.computeIfAbsent(key, k -> new CopyOnWriteArrayList<>()).add(message);
    }

    // 获取两个用户之间的所有消息
    public static List<Message> getMessages(Long fromUserId, Long toUserId) {
        String key = generateKey(fromUserId, toUserId);
        String reverseKey = generateKey(toUserId, fromUserId);

        // 创建一个新列表来保存合并后的消息
        List<Message> combinedMessages = new ArrayList<>();

        // 安全地获取两个方向的消息列表，并添加到合并列表中
        addAllIfPresent(messageStore, key, combinedMessages);
//        addAllIfPresent(messageStore, reverseKey, combinedMessages);

        // 对合并后的列表按照时间戳排序
        combinedMessages.sort(Comparator.comparing(Message::getTimestamp));

        return combinedMessages;
    }

    private static void addAllIfPresent(
            ConcurrentHashMap<String, CopyOnWriteArrayList<Message>> store,
            String key,
            List<Message> target) {
        CopyOnWriteArrayList<Message> messages = store.get(key);

        if (messages != null) {
            target.addAll(messages);
        }
    }

    // 生成唯一的消息键
    private static String generateKey(Long userId1, Long userId2) {
        return userId1 < userId2 ? userId1 + ":" + userId2 : userId2 + ":" + userId1;
    }
}
